/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tbgb.bml;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import javax.microedition.midlet.MIDlet;

/**
 *
 * @author LưuQuang
 */
public class BMLDocumentBuilder {
    private static final int DEFAULT_MAX_VALUE_LENGTH = 1024;
    
    private int maxValueLength = DEFAULT_MAX_VALUE_LENGTH;
    
    private BMLDocumentBuilder()
    {
        
    }
    
    private static BMLDocumentBuilder inst = new BMLDocumentBuilder();
    
    public static BMLDocumentBuilder getInstance()
    {
        return inst;
    }
    
    public BMLDocument createDocument(InputStream is) throws IOException
    {
        DataInputStream dIs = new DataInputStream(is);
        
        Long rootCode = this.getRootCode(dIs);
        Hashtable bmlData = this.parseBML(dIs);
        
        dIs.close();
        
        return new BMLDocumentImpl(bmlData, rootCode);
    }
    
    private Long getRootCode(DataInputStream s) throws IOException
    {
        long rootCode = s.readLong();
        
        return new Long(rootCode);
    }
    
    private Hashtable parseBML(DataInputStream s) throws IOException
    {
        byte[] buffer = new byte[maxValueLength];
        Hashtable data = new Hashtable();
        int nElem = s.readInt();
        for (int i = 0; i < nElem; ++i)
        {
            long key = s.readLong();
            int valueLength = s.readInt();
            
            s.read(buffer, 0, valueLength);
            String value = new String(buffer, 0, valueLength);
            
            data.put(new Long(key), value);
            System.out.println(key + ": " + value);
        }
        
        return data;
    }

    /**
     * @return the maxValueLength
     */
    public int getMaxValueLength() {
        return maxValueLength;
    }

    /**
     * @param maxValueLength the maxValueLength to set
     */
    public void setMaxValueLength(int maxValueLength) {
        this.maxValueLength = maxValueLength;
    }
}
